import { Provide, Inject, Config } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entity/user';
import { MidwayHttpError } from '@midwayjs/core';
import { CacheManager } from '@midwayjs/cache';
import { Context } from '@midwayjs/koa';
import { Role } from '../entity/role';
import { JwtService } from '@midwayjs/jwt';
import { checkCode } from '../utils/checkCode';

@Provide()
export class UserService {
  @InjectEntityModel(User)
  userModel: Repository<User>;

  @InjectEntityModel(Role)
  roleModel: Repository<Role>;

  @Config('jwt')
  config: any;

  @Inject()
  cacheManager: CacheManager;

  @Inject()
  ctx: Context;

  @Inject()
  jwtService: JwtService;
  // @Inject()
  // entityManager: EntityManager;

  async register(data: any) {
    const { username, password, email, code, roleCode, codeKey } = data;

    let result: any = await this.userModel.findOne({
      where: { username },
    });
    if (result) {
      throw new MidwayHttpError('用户已被注册!', 500);
    }

    if (email) {
      result = await this.userModel.findOne({
        where: { email },
      });
      if (result) {
        throw new MidwayHttpError('邮箱已被注册!', 500);
      }
    }

    const role: any = await this.roleModel.findOne({
      where: { code: roleCode },
    });

    const user = new User();
    user.name = this.ctx.security.escape(username);
    user.username = this.ctx.security.escape(username);
    user.email = email || '';
    user.password = password;
    user.avatar = 'https://cdn.1024jiaocheng.cn/noavatar_small.gif';
    user.grade = 1;
    user.role = role;

    const cacheCode = await this.cacheManager.get(codeKey);

    if (!code || code.toLowerCase() !== cacheCode) {
      throw new MidwayHttpError('验证码错误!', 500);
    }

    this.cacheManager.set(codeKey, '&(&$#$sldfj79131', {
      ttl: 100,
    });

    result = await this.userModel.save(user);

    return {
      code: 200,
      data: result,
      message: '注册成功!',
    };
  }

  async login(data: any) {
    const { username, password, codeKey, code } = data;

    if (!username || !password) {
      throw new MidwayHttpError('用户名或者密码不能为空!', 500);
    }

    const cacheCode = await this.cacheManager.get(codeKey);
    checkCode(cacheCode, code);

    const result = await this.userModel.findOne({
      where: { username: username, password: password },
      relations: ['role'],
    });

    if (!result) {
      throw new MidwayHttpError('用户名或者密码错误!', 500);
    }

    const token = await this.jwtService.sign(
      { userId: result.id, roleId: result.role.id, roleCode: result.role.code },
      this.config.secret,
      {
        expiresIn: '48h',
      }
    );

    return {
      code: 200,
      data: { ...result, token },
      message: '登录成功!',
    };
  }
}
